package com.example.patentback.service.impl;

import com.example.patentback.dao.SysRoleMapper;
import com.example.patentback.entity.SysRole;
import com.example.patentback.service.SysRoleService;
import com.example.patentback.util.Const;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Autowired
    SysRoleMapper sysRoleMapper;

    @Override
    public SysRole selectById(Long id) {
        Example example = new Example(SysRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", id);
        return sysRoleMapper.selectByExample(example).get(0);
    }

    @Override
    public List<SysRole> selectByName(String name, int current, int size) {

        int pageNum = current;
        int pageSize = size;
        int start = (pageNum - 1) * pageSize;
        RowBounds rowBounds = new RowBounds(start, pageSize);
        if (name == null) {
            return sysRoleMapper.selectByRowBounds(new SysRole(), rowBounds);
        } else {
            Example example = new Example(SysRole.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.orLike("name", "%" + name + "%");
            return sysRoleMapper.selectByExampleAndRowBounds(example, rowBounds);
        }
    }

    @Override
    public SysRole saveSysRole(SysRole sysRole) {
        sysRole.setCreated(new Date());
        sysRole.setStatu(Const.STATUS_ON);
        sysRoleMapper.insert(sysRole);
        return sysRole;
    }

    @Override
    public SysRole updateSysRole(SysRole sysRole) {
        sysRole.setUpdated(new Date());
        sysRoleMapper.updateByPrimaryKey(sysRole);
        return sysRole;
    }

    @Override
    public int deleteSysRoles(Long[] roleIds) {
        Example example = new Example(SysRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id", Arrays.asList(roleIds));
        return sysRoleMapper.deleteByExample(example);
    }

    @Override
    public List<SysRole> selectSysRoleByRoleIds(List<Long> roleIds) {
        Example example = new Example(SysRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id", roleIds);
        return sysRoleMapper.selectByExample(example);
    }
}
